import { Component, OnInit, Input } from '@angular/core';
// 导入表单相关：表单验证、表单构建、表单组
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { LibraryService } from 'src/app/core/service/library.service';
import { parse } from 'url';

@Component({
  selector: 'app-library-modal',
  templateUrl: './library-modal.component.html',
  styleUrls: ['./library-modal.component.scss']
})
export class LibraryModalComponent implements OnInit {
  @Input() title: string;
  @Input() subtitle: string;
  libraryForm: FormGroup;
  librarySeniorForm: FormGroup;
  data = {};
  // tabs分页
  tabs = ['通用', '高级'];
  // select-part
  listOfOption: Array<{ name: string; value: string }> = [];
  selectValue = [];
  constructor(
    private modal: NzModalRef,
    private message: NzMessageService,
    private libraryService: LibraryService,
    fb: FormBuilder
  ) {
    // === old ===
    // this.libraryForm = fb.group({
    //   artifactName: [null, Validators.required],
    //   dateProfiled: [null], 
    //   grade: [null, Validators.required],
    //   groupName: [null, Validators.required],
    //   hash: [null, Validators.required],
    //   latestReleaseDate: [null],
    //   latestVersion: [null],
    //   releaseDate: [null],
    //   version: [null],
    //   versionsBehind: [null],
    //   licenseIds: [null, Validators.required],
    // });
    //
    // addLibrary(): void {
    //   console.log(this.libraryForm.controls);
    //   // tslint:disable-next-line:forin
    //   for (const c in this.libraryForm.controls) {
    //     this.libraryForm.controls[c].markAsTouched();
    //   }
    //   if (this.libraryForm.valid) {
    //     this.data = {
    //       artifactName: this.libraryForm.value.artifactName,
    //       dateProfiled: null,
    //       grade: this.libraryForm.value.grade,
    //       groupName: this.libraryForm.value.groupName,
    //       hash: this.libraryForm.value.hash,
    //       latestReleaseDate: null,
    //       latestVersion: null,
    //       releaseDate: null,
    //       version: null,
    //       versionsBehind: null,
    //       licenseIds: this.libraryForm.value.grade
    //     };
    //     console.log(' ====this.data === ', this.data);
    //     this.libraryService.addLibrary(this.data).subscribe((addResult) => {
    //       this.result = result;   // 返回的结果
    //       console.log('==result==', addResult);
    //       if (addResult.status === 1 && addResult.msg === 'OK') {
    //         this.message.success('添加成功!', {
    //           nzDuration: 10000
    //         });
    //         this.modal.destroy({ data: 'this the result data' });
    //       } else {
    //         this.message.error('添加失败!请检查后重新填写', {
    //           nzDuration: 10000
    //         });
    //       }
    //     });
    //   } else {
    //     this.message.error('表单校验失败', { nzDuration: 10000 });
    //   }
    // }
    // === new ===
    this.libraryForm = fb.group({
      artifactName: [null, Validators.required], // 组件名称
      version: [null, Validators.required], // 版本号
      groupName: [null, Validators.required], // 组织名称
      licenseIds: [null, Validators.required], // 许可
      hash: [null],
      cveName: [null], // cve编号
      latestReleaseDate: [null], // 最近发布日期
      releaseDate: [null], // 首次发布日期
      latestVersion: [null] // 版本号
    });
  }

  addLibrary(): void {
    // tslint:disable-next-line:forin
    for (const c in this.libraryForm.controls) {
      this.libraryForm.controls[c].markAsTouched();
    }

    if (this.libraryForm.valid) {
      this.data = {
        artifactName: this.libraryForm.value.artifactName,
        version: this.libraryForm.value.version,
        groupName: this.libraryForm.value.groupName,
        licenseId: this.libraryForm.value.licenseIds,
        hash: this.libraryForm.value.hash,
        cves: this.libraryForm.value.cveName ? this.postDataFormat(this.libraryForm.value.cveName) : '',
        // tslint:disable-next-line: max-line-length
        latestReleaseDate: this.libraryForm.value.latestReleaseDate ? ((this.libraryForm.value.latestReleaseDate).getTime()).toString() : '',
        latestVersion: this.libraryForm.value.latestVersion,
        releaseDate: this.libraryForm.value.releaseDate ? ((this.libraryForm.value.releaseDate).getTime()).toString() : ''
      };
      console.log(' ====this.data === ', this.data);
      this.postAddData(this.data);
      // window.localStorage.removeItem('ifLibrarySecond');
      // window.localStorage.removeItem('secondLibraryForm');
    } else {
      this.message.error('表单校验失败!请检查表单', { nzDuration: 10000 });
    }
  }
  // post-format
  postDataFormat(val: string) {
    let arr = val.split(',');
    let cveNameArr = [];
    let cveNameObj = {};
    if (arr.length) {
      for (let i = 0; i < arr.length; i++) {
        cveNameObj = {
          cveName: arr[i]
        }
        cveNameArr.push(cveNameObj)
      }
    }
    console.log('formatData==', cveNameArr);

    return cveNameArr;
  }
  // postAdd
  postAddData(data) {
    this.libraryService.addLibrary(data).subscribe((addResult) => {
      // this.result = addResult;   // 返回的结果
      console.log('==result==', addResult);
      if (addResult.status === 1 && addResult.msg === 'OK') {
        this.message.success('添加成功!', {
          nzDuration: 10000
        });
        // window.localStorage.removeItem('ifLibrarySecond');
        // window.localStorage.removeItem('secondLibraryForm');
        this.modal.destroy({ data: 'this the result data' });
      } else {
        this.message.error('添加失败!请检查后重新填写', {
          nzDuration: 10000
        });
      }
    });
  }
  destroyModal(): void {
    // this.getSecondForm('set');
    this.modal.destroy({ data: 'this the result data' });
  }
  getSelectLicenseId() {
    this.libraryService.getSelectLicenseId().subscribe(selectData => {
      console.log("selectData", selectData);
      if (selectData.status === 1) {
        // select-part
        const children = [];
        for (let i = 0; i < selectData.data.length; i++) {
          children.push({ name: selectData.data[i].name, value: selectData.data[i].value });
        }
        this.listOfOption = children;
      }
    });
  }
  // 获取未提交的表单数据
  // getSecondForm(type) {
  //   if (type === 'set') { // 存储未提交的表单
  //     let data = {
  //       artifactName: this.libraryForm.value.artifactName ? this.libraryForm.value.artifactName : null,
  //       version: this.libraryForm.value.version ? this.libraryForm.value.version : null,
  //       groupName: this.libraryForm.value.groupName ? this.libraryForm.value.groupName : null,
  //       licenseIds: this.libraryForm.value.licenseIds ? this.libraryForm.value.licenseIds : null,
  //       hash: this.libraryForm.value.hash ? this.libraryForm.value.hash : null,
  //       cveName: this.libraryForm.value.cveName ? this.libraryForm.value.cveName : null,
  //       latestReleaseDate: this.libraryForm.value.latestReleaseDate ? this.libraryForm.value.latestReleaseDate : null,
  //       latestVersion: this.libraryForm.value.latestVersion ? this.libraryForm.value.latestVersion : null,
  //       releaseDate: this.libraryForm.value.releaseDate ? this.libraryForm.value.releaseDate : null
  //     };
  //     window.localStorage.setItem('secondLibraryForm', JSON.stringify(data));
  //     window.localStorage.setItem('ifLibrarySecond', '1');
  //     console.log('=-=', this.libraryForm.value);
  //   } else if (type === 'get') { // 获取上一次未提交的表单
  //     let jsonObj = JSON.parse(window.localStorage.getItem('secondLibraryForm'));
  //     for (let i = 0; i < jsonObj.licenseIds.length; i++) {
  //       this.selectValue.push(jsonObj.licenseIds[i]);
  //     }
  //     console.log('YY', this.selectValue);
  //     this.libraryForm.patchValue({
  //       artifactName: jsonObj.artifactName,
  //       version: jsonObj.version,
  //       groupName: jsonObj.groupName,
  //       // licenseIds: this.selectValue,
  //       hash: jsonObj.hash,
  //       cveName: jsonObj.cveName,
  //       latestReleaseDate: jsonObj.latestReleaseDate,
  //       latestVersion: jsonObj.latestVersion,
  //       releaseDate: jsonObj.releaseDate
  //     });
  //     console.log('-=-', this.libraryForm.value);
  //   }
  // }
  ngOnInit() {
    // select-part-format
    this.getSelectLicenseId();

    // get-formData
    // if (window.localStorage.getItem('ifLibrarySecond') === '1') {
    //   this.getSecondForm('get');
    // }
  }

}
